<template lang="pug">
image.aimg.class(:src="url" @click="methods._preview" :mode="mode" lazy-load="true" :class="{bg: !src}")
</template>
<script>
import {host, imgRootDir} from '@/common/config/app.json'
import {computed, ref} from 'vue'
export default {
  options: {// 微信小程序组件默认设置
    styleIsolation: 'apply-shared',
    virtualHost: true
  },
  externalClasses: ['class'],// 微信小程序组件默认设置
  props: {
    src: {type: [String, Number], default: ''},
    mode: {type: String, default: 'aspectFill'},
    // 缩写支持
    local: {type: Boolean, default: false},
    png: {type: Boolean, default: false},
    jpg: {type: Boolean, default: false},
    svg: {type: Boolean, default: false},
    // 预览
    preview: {type: Boolean, default: false}
  },
  setup(props){
    const url = computed(()=>{
      let {src, local} = props
      if(!src.length) return ''
      if(local){
        src = (imgRootDir + src).replace(/\/\//g, '/')
      }else{
        ['png', 'jpg', 'svg'].forEach((mime)=>{ 
          if(props[mime]) src = `${imgRootDir}/${mime}/${src}.${mime}`.replace(/\/\//g, '/')
        }) 
      }
      let flag = src.indexOf('http') == -1 &&  src.indexOf(host) == -1 &&  src.indexOf('data:image') == -1
      // #ifdef H5
      flag = flag && process.env.NODE_ENV != 'production'
      // #endif
      return (flag && src.indexOf(imgRootDir) == -1)? (host+src).replace(/\/\//g, '/').replace(/:\/([^\/])/, '://$1'): src
    })

    const methods = {
      _preview(){
        props.preview && uni.previewImage({ urls: [url.value] })
      }
    }

    return {
      url,
      methods
    }
  },
}
</script>
<style lang="scss" scope>
.aimg{
  display: var(--aimg-display, block);
  width: var(--aimg-width, 32rpx); 
  height: var(--aimg-height, var(--aimg-width, 32rpx)); 
  border-radius: var(--aimg-border-radius, inherit);
  &.bg{
    background-color: #ccc;
  }
}
</style>